package com.forum.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.forum.model.dao.ForumUserDAO;
import com.forum.model.pojo.ForumUser;

@WebServlet("/LoginController")
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		String path = request.getHeader("referer");
		
		String lang = request.getParameter("lang");
		lang = (lang != null) ? "?lang=" + lang : "";
		
		if(!path.contains("section") && !path.contains("topic")){
			path = request.getServletContext().getContextPath() + "/index.jsp" + lang;
		}

		if(session.getAttribute("user") != null){
			session.invalidate();
			response.sendRedirect(path);
		}else{
			String userName = request.getParameter("username");
			ForumUser user = new ForumUserDAO().getUserByLoginName(userName);
			boolean grantAccess = false;
			String message = "";
			
			if(user != null){
				String passHashed = String.valueOf(request.getParameter("password").hashCode());
				
				if(user.getPassHash().equals(passHashed)){
					session.setAttribute("user", user);
					response.sendRedirect(path);
					return;
				}
				
				else message = ":Wrong password!";
			}else{
				message = ":No such user!";
			}
			
			PrintWriter out = response.getWriter();
			out.write(String.valueOf(grantAccess) + message);
			out.close();
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
}